package com.gusti.turnos.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.gusti.turnos.dao.IUserDao;
import com.gusti.turnos.exception.TurnosException;
import com.gusti.turnos.model.User;
import com.gusti.turnos.util.Debug;

/**
 * 
 * @author gusti
 *
 */
@Repository
public class UserDao extends ProjectDao<User> implements IUserDao {

	@SuppressWarnings("unchecked")
	@Override
	public List<User> retrieveUsers() {

		List<User> user = new ArrayList<User>();
		Query query = null;
		try {
			query = em.createQuery( "FROM User as u ORDER BY u.name" );
			user = (List<User>)query.getResultList();
		} catch ( Exception e ) {
			Debug.error( e );
			throw new TurnosException( e );
		}

		return user;
	}

	@Override
	public User retrieveUser( long id ) {

		User user = new User();
		Query query = null;
		try {
			query = em.createQuery( "FROM User WHERE id = :id" );
			query.setParameter( "id", id );
			user = (User)query.getSingleResult();
		} catch ( Exception e ) {
			Debug.error( e );
			throw new TurnosException( e );
		}

		return user;
	}

	@Override
	public User retrieveUserByStringField( String field, String value ) {

		User user = new User();
		Query query = null;
		try {
			query = em.createQuery( "FROM User WHERE " + field + " = :value" );
			query.setParameter( "value", value );
			user = (User)query.getSingleResult();
		} catch ( Exception e ) {
			Debug.error( e );
			throw new TurnosException( e );
		}

		return user;
	}
}
